<?php

namespace App\Core;

use App\Core\Exception\DefaultException;
use App\Core\Exception\LoginException;
use App\Util\ArrayHelper;
use EasySwoole\Component\Singleton;

/**
 * Class Result
 *
 * @property int $statusCode 错误码
 * @property string $msg 提示信息
 * @property array $data 返回数据
 * @property-read bool $isSuccess 是否返回正确
 *
 */
class Output{
    
    /**
     * @var int 错误码
     */
    private $_statusCode;
    /**
     * @var string 提示信息
     */
    private $_msg;
    /**
     * @var array 返回数据
     */
    private $_data;
    
    /**
     * 设置错误码
     * @param int $statusCode 错误码
     * @return self
     */
    public function setStatusCode($statusCode){
        $this->_statusCode = $statusCode;
        return $this;
    }
    
    /**
     * 设置提示信息
     * @param string $errmsg 错误码
     * @return self
     */
    public function setMsg($errmsg){
        $this->_msg = $errmsg;
        return $this;
    }
    
    /**
     * 设置返回数据
     * @param array $data 返回数据
     * @return self
     */
    public function setData($data){
        $this->_data = $data;
        return $this;
    }
    
    /**
     * 获取错误码
     * @return int
     */
    public function getStatusCode(){
        return $this->_statusCode;
    }
    
    /**
     * 获取提示信息
     * @return string
     */
    public function getMsg(){
        return $this->_msg;
    }
    
    /**
     * 获取返回数据
     * @return array
     */
    public function getData(){
        return $this->_data;
    }
    
    /**
     * 是否返回正确
     * @return bool
     */
    public function getIsSuccess(){
        return $this->_statusCode === 200;
    }
    
    public function pushData($data, $val = ''){
        if(is_array($data)){
            $this->_data = ArrayHelper::merge($this->_data, $data);
        }else{
            $this->_data[$data] = $val;
        }
        
        return $this;
    }
    
    public function toString(){
        return json_encode([
            'code' => $this->_statusCode,
            'msg'  => $this->_msg,
            'data' => $this->_data,
        ], JSON_UNESCAPED_UNICODE);
    }
    
    public function __get($name){
        $getter = 'get' . $name;
        if(method_exists($this, $getter)){
            return $this->$getter();
        }
        
        throw new DefaultException('Getting unknown property: ' . get_class($this) . '::' . $name);
    }
    
    public function __set($name, $value){
        $setter = 'set' . $name;
        if(method_exists($this, $setter)){
            $this->$setter($value);
        }
        throw new DefaultException('Getting unknown property: ' . get_class($this) . '::' . $name);
    }
}